package ddu.com.intercept;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Calendar;

import static java.util.Calendar.HOUR_OF_DAY;

/**
 * @author:zhangxia
 * @createTime: 2018/4/16 17:59
 * @version:1.0
 * @desc:添加拦截器
 */
@Slf4j
@Data
public class MyInterceptor extends HandlerInterceptorAdapter {

    private int openingTime = 8;
    private int closingTime = 23;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("request = [" + request + "], response = [" + response + "], handler = [" + handler + "]");
        log.info("进入拦截器,类名："+MyInterceptor.class.getName());

        Calendar cal = Calendar.getInstance();
        int hour = cal.get(HOUR_OF_DAY);
        if (openingTime <= hour && hour < closingTime) {
            return true;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charst=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("请在上班期间访问");
        writer.close();
        return false;
    }
}
